<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'
import { userInfoService, deleteUserService } from '@/api/user.js'
import { useTokenStore } from '@/stores/token.js'

const tokenStore = useTokenStore()
const currentUserAccount = tokenStore.userAccount

const userInfo = ref([])

const queryAllExistUser = async () => {
    let result = await userInfoService()
    if (result.code === 200) {
        userInfo.value = result.data.userQueryAllVos
    } else {
        ElMessage.error('服务异常!')
    }
}

queryAllExistUser()

// 计算属性，用于确定删除按钮是否禁用
const isDeleteButtonDisabled = (row) => {
    return row.userAccount === 'root' || currentUserAccount !== 'root'
}

const handleDelete = async (row) => {
    if (currentUserAccount === 'root' && row.userAccount !== 'root') {

        ElMessageBox.confirm(
            '您确认要删除吗?',
            '温馨提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                let result = await deleteUserService(row.userId)
                if (result.code === 200) {
                    ElMessage.success('删除成功!')
                    //重新获取列表
                    queryAllExistUser()
                } else {
                    ElMessage.error('删除失败!')
                }
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消删除',
                })
            })
    } else {
        ElMessage.warning('您无权删除该用户！')
    }
}
</script>


<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>用户管理</span>
            </div>
        </template>
        <el-table :data="userInfo" style="width: 100%">
            <el-table-column label="序号" width="100" type="index"> </el-table-column>
            <el-table-column label="用户" prop="userAccount"></el-table-column>
            <el-table-column label="角色" prop="userRoleDescriptive"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Delete" circle plain type="danger" :disabled="isDeleteButtonDisabled(row)"
                        @click="handleDelete(row)">
                    </el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>